import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, Alert } from 'react-native';
import { useNavigation, useRoute, RouteProp } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';

type RootStackParamList = {
  Xinmi: {
    username?: string;
    from?: 'Youzhao' | 'Shouzhao';
  };
  Denglu: undefined;
};

type NavigationProp = NativeStackNavigationProp<RootStackParamList, 'Xinmi'>;
type XinmiRouteProp = RouteProp<RootStackParamList, 'Xinmi'>;

const ResetPasswordScreen = () => {
  const navigation = useNavigation<NavigationProp>();
  const route = useRoute<XinmiRouteProp>();
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isFormValid, setIsFormValid] = useState(false);
  const [passwordError, setPasswordError] = useState('');
  const [confirmPasswordError, setConfirmPasswordError] = useState('');
  const [username, setUsername] = useState('');

  useEffect(() => {
    // 获取路由参数中的用户名
    if (route.params?.username) {
      setUsername(route.params.username);
    }
  }, [route.params]);

  const validateForm = () => {
    const isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(password);
    const isConfirmPasswordValid = password === confirmPassword && confirmPassword.length > 0;

    setPasswordError(isPasswordValid ? '' : '密码必须包含大写字母、小写字母和数字，且长度至少6位');
    setConfirmPasswordError(
      confirmPassword.length === 0 ? '' : (isConfirmPasswordValid ? '' : '两次密码输入不一致')
    );

    setIsFormValid(isPasswordValid && isConfirmPasswordValid);
  };

  const handleSubmit = async () => {
    if (isFormValid && username) {
      try {
        const response = await fetch('http://192.168.78.1:3000/users/reset-password', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username,
            newPassword: password
          })
        });

        const data = await response.json();
        
        if (response.ok) {
          Alert.alert('成功', '密码重置成功');
          navigation.navigate('Denglu');
        } else {
          Alert.alert('错误', data.message || '密码重置失败');
        }
      } catch (error) {
        console.error('重置密码失败:', error);
        Alert.alert('错误', '网络错误，请重试');
      }
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backBtn} onPress={() => navigation.goBack()}>
          <Text style={styles.backBtnText}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>重置密码</Text>
      </View>
      <View style={styles.form}>
        <TextInput 
          style={[styles.input, passwordError ? styles.inputError : null]} 
          placeholder="输入新密码" 
          placeholderTextColor="#bbb" 
          secureTextEntry
          value={password}
          onChangeText={(text) => {
            setPassword(text);
          }}
          onBlur={validateForm}
        />
        {passwordError ? <Text style={styles.errorText}>{passwordError}</Text> : null}
        <TextInput 
          style={[styles.input, confirmPasswordError ? styles.inputError : null]} 
          placeholder="确认新密码" 
          placeholderTextColor="#bbb" 
          secureTextEntry
          value={confirmPassword}
          onChangeText={(text) => {
            setConfirmPassword(text);
          }}
          onBlur={validateForm}
        />
        {confirmPasswordError ? <Text style={styles.errorText}>{confirmPasswordError}</Text> : null}
        <TouchableOpacity 
          style={[styles.submitBtn, !isFormValid && styles.submitBtnDisabled]} 
          onPress={handleSubmit}
          disabled={!isFormValid}
        >
          <Text style={[styles.submitBtnText, !isFormValid && styles.submitBtnTextDisabled]}>确认并前往登录</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    marginBottom: 10,
    position: 'relative',
  },
  backBtn: {
    position: 'absolute',
    left: 10,
    top: 0,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 10,
    zIndex: 1,
  },
  backBtnText: {
    fontSize: 22,
    color: '#333',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  form: {
    paddingHorizontal: 20,
    flex: 1,
    top: 50,
  },
  input: {
    height: 40,
    backgroundColor: '#f5f5f5',
    borderRadius: 5,
    paddingHorizontal: 10,
    marginBottom: 15,
    fontSize: 14,
  },
  submitBtn: {
    backgroundColor: '#d32f2f',
    borderRadius: 5,
    height: 45,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
  },
  submitBtnDisabled: {
    backgroundColor: '#cccccc',
  },
  submitBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  submitBtnTextDisabled: {
    color: '#666666',
  },
  errorText: {
    color: 'red',
    fontSize: 12,
    marginBottom: 5,
  },
  inputError: {
    borderColor: 'red',
    borderWidth: 1,
  },
});

export default ResetPasswordScreen;
